package com.rizzo.analytics.domain.errors;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.rizzo.infrastructure.web.validator.Save;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;

public class Errors implements Serializable {

    private static final long serialVersionUID = 4L;

    @Valid
    @Size(min = 1, message = "errors.errorcodecount.empty", groups = {Save.class})
    private List<Error> errorCodeCount;

    public Errors() {
    }

    public Errors(List<Error> errorCodeCount) {
        this.errorCodeCount = errorCodeCount;
    }

    public List<Error> getErrorCodeCount() {
        if (errorCodeCount == null) {
            errorCodeCount = Lists.newArrayList();
        }
        return errorCodeCount;
    }

    public void setErrorCodeCount(List<Error> errorCodeCount) {
        this.errorCodeCount = errorCodeCount;
    }

    public Error getError(final String code) {
        Predicate<Error> isService = new Predicate<Error>() {
            @Override
            public boolean apply(Error error) {
                return error.getCode().equals(code);
            }
        };
        Iterable<Error> filteredService = Iterables.filter(getErrorCodeCount(), isService);
        return Iterables.getFirst(filteredService, null);
    }

    public void merge(Errors update) {
        if (update != null && update.getErrorCodeCount() != null) {
            for (Error error : update.getErrorCodeCount()) {
                Error errorWithCode = getError(error.getCode());
                errorWithCode.addCount(error.getCount());
            }
        }
    }

    @Override
    public boolean equals(Object o) {
        return EqualsBuilder.reflectionEquals(this, o);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}
